import {getRequest} from "./api";

export const initMenu=(router,store)=>{
    //store 中有菜单信息，直接return
    if (store.state.routes.length>0){
        return;
    }
    getRequest("/sys/config/menu").then(resp=>{
        if (resp){
            //格式化
            let result=fmtRoutes(resp);
            //放到路由中
            router.addRoutes(result);
            //存放到store.state中
            store.commit('initRoutes',result)
            // console.log(resp);
        }
    })
}

export const fmtRoutes=(routes)=>{
    let fmRoutes=[];
    routes.forEach((router,i)=>{
        let {
            path,
            name,
            icon,
            component,
            children
        }= router;
        if (children&&children instanceof Array){
            children = fmtRoutes(children);
        }
        let route = {
            path:path,
            name:name,
            icon:icon,
            children:children,
            component:(resolve)=>{
                if (component.startsWith('Reg')){
                    require(['@/views/reg/'+component+'.vue'],resolve)
                }else if (component.startsWith('Doc')){
                    require(['@/views/doc/'+component+'.vue'],resolve)
                }else if (component.startsWith('Tech')) {
                    require(['@/views/tech/' + component + '.vue'], resolve)
                }else if (component.startsWith('Shop')) {
                    require(['@/views/shop/' + component + '.vue'], resolve)
                }else if (component.startsWith('Cost')) {
                    require(['@/views/cost/' + component + '.vue'], resolve)
                }else if (component.startsWith('Sys')) {
                    require(['@/views/sys/' + component + '.vue'], resolve)
                }else if (component.startsWith('Home')) {
                    require(['@/views/' + component + '.vue'], resolve)
                }
            }
        }
        fmRoutes.push(route);
    })
    return fmRoutes;

}
